<script setup lang="ts">
import BenchCollectLeft from "@/assets/svg/bench_collect_left.svg?component";
import BenchCompWrapper from "./BenchCompWrapper.vue";
import { queryTreeMenuList, createMenuCollect, queryMenuCollectList, deleteMenuCollect, TreeItem } from "@/api/bench";
import { onMounted, reactive, toRefs, ref } from "vue";
import { PxMessageBox, PxMessage } from "px-ui";
import { useRouter } from "vue-router";
const scrollbarRef = ref();
const router = useRouter();
defineOptions({
  name: "BenchCollect"
});
const state = reactive<{
  isDel: Boolean;
  actionForm: { treeSelect: number[] };
  rules: Record<string, any>;
  isDrawerShow: Boolean;
  treeMenuList: Array<TreeItem>;
  coloctList: Array<Record<string, any>>;
  loading: boolean;
  submitLoading: boolean;
}>({
  isDel: false,
  isDrawerShow: false,
  actionForm: { treeSelect: null },
  rules: { treeSelect: [{ required: true, message: "请选择菜单", trigger: "blur" }] },
  treeMenuList: [],
  coloctList: [],
  loading: false,
  submitLoading: false
});
const { isDel, isDrawerShow, actionForm, rules, treeMenuList, coloctList, loading, submitLoading } = toRefs(state);
const ruleFormRef = ref();
const treeRef = ref();
const defaultProps = {
  children: "children",
  label: "title"
};
onMounted(async () => {
  await queryTreeList();
  await getColoctList();
});
async function handlePlus() {
  isDrawerShow.value = true;
}
function handleMinus() {
  isDel.value = !isDel.value;
}
function handleDelItem(item) {
  const { id, resourceId, title } = item;
  PxMessageBox.confirm(`确认删除${title}`, "提示", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  }).then(async () => {
    const data = await deleteMenuCollect({ id, resourceId });
    if (data) {
      PxMessage.success("删除成功!");
      await getColoctList();
    }
  });
}
function handelCancel() {
  isDrawerShow.value = false;
  // actionForm.value.treeSelect = null;
  setSelect();
}
async function handleSubmit() {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      const selectNode = treeRef.value.getCheckedNodes(true);
      const menuCollect = selectNode.map(item => {
        const { id: resourceId, title, path, permissions, icon } = item;
        return { resourceId, title, path, permissions, icon };
      });
      submitLoading.value = true;
      try {
        await createMenuCollect({ menuCollect });
        await getColoctList();
        isDrawerShow.value = false;
      } catch (error) {}
      submitLoading.value = false;
    } else {
      console.log("error submit!", fields);
    }
  });
}
async function queryTreeList() {
  treeMenuList.value = await queryTreeMenuList();
  // addKeyValueToTreeByField(treeMenuList.value, "disabled", "isJump");
}
async function getColoctList() {
  loading.value = true;
  try {
    coloctList.value = (await queryMenuCollectList()) || [];
  } catch (error) {}
  loading.value = false;
  setSelect();
}
function setSelect() {
  let select = [];
  coloctList.value.forEach(item => {
    if (item.resourceId) {
      select.push(item.resourceId);
    }
  });
  actionForm.value.treeSelect = select;
}
function coloctClick(item) {
  if (isDel.value) return;
  const { path } = item;

  router.push({
    path
  });
}
const filterNodeMethod = (value, data) => {
  return data?.title?.includes(value);
};
</script>

<template>
  <div class="collect-box">
    <BenchCompWrapper class="collect-wrapper" title="我的收藏">
      <template v-slot:btn>
        <div class="btn-group">
          <div class="btn-item" @click="handlePlus">
            <px-icon><AddRectangle /></px-icon><span class="btn-text">添加</span>
          </div>
          <div v-if="!isDel" class="btn-item" @click="handleMinus">
            <px-icon><Delete /></px-icon><span class="btn-text">移除</span>
          </div>
          <div v-else class="btn-item" @click="handleMinus">
            <px-icon><MinusRectangle /></px-icon><span class="btn-text">取消</span>
          </div>
        </div>
      </template>
      <template v-slot:content>
        <div v-if="coloctList && coloctList.length > 0" class="bench-collect">
          <px-scrollbar ref="scrollbarRef">
            <div class="bench-collect-warpper">
              <div v-for="item in coloctList" :key="item.id" class="bench-collect-common bench-collect-item" @click="coloctClick(item)">
                <div class="bench-collect-item-top">
                  <BenchCollectLeft />
                  <px-button v-if="isDel" circle class="bench-del-btn" icon="Minus" @click.stop="handleDelItem(item)" />
                </div>
                <p class="self-end page-name">{{ item.title }}</p>
              </div>
            </div>
          </px-scrollbar>
        </div>
        <div v-else v-loading="loading" class="bench-collect-empty-warpper">暂未收藏</div>
      </template>
    </BenchCompWrapper>
    <px-dialog v-model="isDrawerShow" title="添加功能" destroy-on-close width="600px" @close="handelCancel">
      <px-form ref="ruleFormRef" class="bench-collect-form" :model="actionForm" :rules="rules" label-width="80px">
        <px-form-item label="功能菜单" prop="treeSelect">
          <px-tree-select
            ref="treeRef"
            v-model="actionForm.treeSelect"
            node-key="id"
            :data="treeMenuList"
            :props="defaultProps"
            :render-after-expand="false"
            :check-strictly="false"
            show-checkbox
            filterable
            clearable
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="3"
            :filter-node-method="filterNodeMethod"
            multiple
          />
        </px-form-item>
      </px-form>

      <template #footer>
        <span class="dialog-footer">
          <px-button @click="handelCancel">取消</px-button>
          <px-button type="primary" :loading="submitLoading" @click="handleSubmit"> 确定 </px-button>
        </span>
      </template>
    </px-dialog>
  </div>
</template>

<style lang="scss" scoped>
.collect-box {
  flex-grow: 1;
}

.collect-wrapper {
  height: 128px;
}

.page-name {
  position: absolute;
  top: 50%;
  right: 8px;
  display: -webkit-box;
  width: 95px;
  overflow: hidden;
  word-break: break-all;
  transform: translateY(-50%);
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.bench-collect {
  display: flex;
  align-items: center;
  padding-top: 12px;

  &-warpper {
    display: flex;
    max-width: calc(100% - 280px);
    height: 100%;
  }

  &-empty-warpper {
    height: 76px;
    font-size: 14px;
    line-height: 76px;
    color: #909399;
    text-align: center;
  }

  &-common {
    display: flex;
    flex-shrink: 0;
    flex-wrap: wrap;
    justify-content: center;
    width: 136px;
    height: 56px;
    padding: 8px;
    margin-right: 16px;
    font-size: 14px;
    font-weight: 700;
    color: #000;
    background-image: url("@/assets/images/bench_collect_bg.png");
    background-repeat: no-repeat;
    background-position: top right;
    border-radius: 4px;

    &:last-child {
      margin-right: 0;
    }
  }

  &-item {
    position: relative;
    box-sizing: border-box;
    align-items: flex-start;
    cursor: pointer;
    background-color: #eff6ff;

    &-top {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;

      .bench-del-btn {
        width: 24px;
        height: 24px;
        font-size: 18px;
        color: #fffaf9;
        background-color: #ff0101;
        position: relative;
        z-index: 9;
      }
    }
  }

  &-plus,
  &-minus {
    align-items: flex-end;
    background: #f7f7f7;
    border: 1px solid #dfdfdf;
  }
}

.btn-group {
  display: flex;
  align-items: center;
  height: 32px;
  color: #3b82f6;

  .btn-item {
    display: flex;
    align-items: center;
    margin-left: 32px;
    cursor: pointer;
  }

  .btn-text {
    margin-left: 2px;
  }
}

.bench-collect-form {
  width: 470px;

  :deep(.px-form-item) {
    width: 100%;
    margin-bottom: 8px;

    .px-input {
      width: 100%;
    }

    .px-select {
      width: 400px;
    }

    .px-select-v2 {
      width: 400px;
    }
  }
}
</style>
